package com.tgd.RingtoneContactManager;

import android.content.Context;
import android.text.TextPaint;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

public class GroupAdapter extends BaseAdapter {

    class ViewHolder {
        Group group;
        TextView tvGroup;
        TextView tvRingtones;
        TextView tvAccount;
        TextView tvNumContacts;
    }

    private Group[] mGroups;
    private LayoutInflater mInflater;

    public GroupAdapter(Context context, Group[] groups) {
        // Cache the LayoutInflate to avoid asking for a new one each time.
        mInflater = LayoutInflater.from(context);
        mGroups = groups;
    }

    @Override
    public int getCount() {
        return mGroups.length;
    }

    @Override
    public Object getItem(int position) {
        return mGroups[position];
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;

        if (convertView == null) {
            convertView = mInflater.inflate(R.layout.group_row, null);

            holder = new ViewHolder();
            holder.tvGroup = (TextView) convertView.findViewById(R.id.tvGroupName);
            holder.tvRingtones = (TextView) convertView.findViewById(R.id.tvGroupRingtones);
            holder.tvNumContacts = (TextView) convertView
                    .findViewById(R.id.tvGroupNumberOfContacts);
            holder.tvAccount = (TextView) convertView.findViewById(R.id.tvGroupAccount);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        Group r = mGroups[position];
        holder.group = r;
        convertView.setTag(holder);

        holder.tvGroup.setText(r.getName());
        holder.tvNumContacts.setText(String.valueOf(r.getContacts().length));
        holder.tvAccount.setText(r.getAccount());
        // TODO Hide or show the default icon based on if the group is set to
        // the default.

        String text = TextUtils.join(", ", r.getRingtones());
        TextPaint p = holder.tvRingtones.getPaint();
        float textWidth = parent.getMeasuredWidth() - holder.tvRingtones.getPaddingLeft()
                - holder.tvRingtones.getPaddingRight() - 100; // TODO figure out
                                                              // to get this
                                                              // measurement
                                                              // better

        holder.tvRingtones.setText(TextUtils
                .commaEllipsize(text, p, textWidth, "1 more", "%d more"));

        return convertView;
    }
}
